package com.qf.commons;

import com.qf.entity.User;
import io.jsonwebtoken.*;

import java.util.Date;

/**
 * JWT签发校验工具
 */
public class JwtUtil {

    private static String key = "qweqwrasd123123w21wqwe2312qwe";

    private static int timeout = 1000 * 60 * 60 * 24 * 7;

    /**
     * 生成令牌
     * @return
     */
    public static String createToken(User user, String devId){

        JwtBuilder builder = Jwts.builder()
                .setId(user.getId() + "")
                .setSubject(user.getNickname())
                .setIssuedAt(new Date())
                //添加自定义属性
                .claim("id",user.getId())
                .claim("nickname", user.getNickname())
                .setExpiration(new Date(new Date().getTime() + timeout))
                .signWith(SignatureAlgorithm.HS256, key + devId);

        String jwtToken = builder.compact();

        return jwtToken;
    }

    /**
     * 验签 - 令牌是否合法
     */
    public static User parseToken(String token, String devId){
        //获得荷载中的私有部分
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(key + devId)
                    .parseClaimsJws(token)
                    .getBody();

            if (claims != null) {
                int id = (Integer)claims.get("id");
                String nickname = (String) claims.get("nickname");

                User user = new User()
                        .setId(id)
                        .setNickname(nickname);
                return user;
            }
        } catch (Exception e) {
        }
        return null;
    }

    //eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxIiwic3ViIjoi5bCP5piOIiwiaWF0IjoxNjAxMDA2MjAzLCJpZCI6MSwibmlja25hbWUiOiLlsI_mmI4iLCJleHAiOjE2MDE2MTEwMDN9.WEERc5_LpK1ZnH8MvSPQlUlU84ByuqcGVPO1s_z4xx0
    public static void main(String[] args) {
//        String token = createToken(new User().setId(1).setNickname("小明"), "124123weqwe");
//        System.out.println(token);

        String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxIiwic3ViIjoi5bCP5piOIiwiaWF0IjoxNjAxMDA2MjAzLCJpZCI6MSwibmlja25hbWUiOiLlsI_mmI4iLCJleHAiOjE2MDE2MTEwMDN9.WEERc5_LpK1ZnH8MvSPQlUlU84ByuqcGVPO1s_z4xx0";

        User user = parseToken(token, "124123w1eqwe");
        System.out.println(user);
    }
}
